package main

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

var DB *gorm.DB
var mysqlLogger logger.Interface

func init() {
	user := "talon"
	password := "Gao123456@1"
	host := "192.168.71.6"
	port := 3306
	dbname := "gorm_learning"
	timeout := "10s"

	mysqlLogger = logger.Default.LogMode(logger.Info)

	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local&timeout=%s", user, password, host, port, dbname, timeout)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		panic("数据库连接失败， error：" + err.Error())
	}
	DB = db
}

type Student struct {
	ID     uint    `gorm:"size:3"`
	Name   string  `gorm:"size:8"`
	Age    int     `gorm:"size:3"`
	Gender string  `gorm:"size:2"`
	Email  *string `gorm:"size:32"`
}

func main() {
	DB = DB.Session(&gorm.Session{
		Logger: mysqlLogger,
	})
	//DB.AutoMigrate(&Student{})
	// 添加记录
	//var students []Student
	//for i := 0; i < 10; i++ {
	//	students = append(students, Student{
	//		Name:   fmt.Sprintf("name %d", i+1),
	//		Age:    7*(i+1) + i,
	//		Gender: "男",
	//		Email:  nil,
	//	})
	//}
	//DB.Create(&students)

	//查询单条记录
	//var s1 Student
	//DB.Take(&s1)
	//fmt.Println(s1)
	//s1 = Student{}
	//DB.First(&s1)
	//fmt.Println(s1)
	//s1 = Student{}
	//DB.Last(&s1)
	//fmt.Println(s1)

	//// 按条件查询
	//err := DB.Take(&s1, 4).Error
	//err := DB.Take(&s1, "name=?", "name 8").Error
	//// 等价写法，但是会sql注入，不建议
	//err := DB.Take(&s1, fmt.Sprintf("name = '%s'", "name 8")).Error
	//fmt.Println(errors.Is(err, gorm.ErrRecordNotFound))
	//fmt.Println(s1)
	//
	//// 根据结构体查询
	//s1.ID = 7
	//DB.Take(&s1)
	//fmt.Println(s1)
	//
	//// 获取查询的记录数
	//fmt.Println(DB.Find(&[]Student{}).RowsAffected)
	//// 获取查询的错误
	//fmt.Println(DB.Find(&[]Student{}).Error)

	//// 查询多条记录
	//var students []Student
	//DB.Find(&students)
	////for _, student := range students {
	////	fmt.Println(student)
	////}
	//data, _ := json.Marshal(students)
	//fmt.Println(string(data))
	//
	//DB.Find(&students, []int{1, 5, 7})
	//fmt.Println(students)
	//DB.Find(&students, "name in (?)", []string{"name 1", "name 2"})
	//fmt.Println(students)

	// 更新操作
	//// 单条记录更新
	//var student Student
	//DB.Take(&student, 11)
	//student.Name = "sdj"
	//DB.Select("name").Save(&student)

	//// 批量更新
	//var students []Student
	////DB.Find(&students, []int{3, 4, 7}).Update("gender", "女")
	////DB.Find(&students, []int{3, 4, 7}).Updates(Student{Age: 40, Gender: "未知", Name: ""})
	//DB.Find(&students, []int{3, 4, 7}).Updates(map[string]any{"age": 41, "Gender": ""})

	// 删除
	var s1 Student
	//DB.Delete(&s1, 11)
	//DB.Delete(&s1, []int{12, 13})
	DB.Take(&s1)
	DB.Delete(&s1)
}
